﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSpecLauncher.Model;

namespace MSpecLauncher.Services
{
    /// <summary>
    /// Creates configuration model from text
    /// </summary>
    public class ConfigBuilder : IConfigBuilder
    {
        private string ON_VAL = "on";
        private string OFF_VAL = "off";

        private string COMMENT_MARK = "#";
        private string AUTODETECT_MARK = "[autodetect changes]";
        private string SHOW_COMMAND_MARK = "[show command window]";
        private string MPSPEC_LOCATION_MARK = "[mspec location]";
        private string ASSEMBLY_MARK = "[assembly]";
        private string OUTPUT_FOLDER_MARK = "[output folder]";


        /// <summary>
        /// Builds configuration from the given text.
        /// Exceptions are propagated.
        /// </summary>
        public Config Build(string configTxt)
        {
            Config config = new Config();

            string[] lines = configTxt.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string line in lines)
            {
                // Ignore comment lines
                if (line.StartsWith(COMMENT_MARK)) continue;

                // Autodetect changes
                if (line.StartsWith(AUTODETECT_MARK))
                {
                    string val = this.GetLineVal(line, AUTODETECT_MARK).ToLower();
                    config.AutodetectChanges = val == ON_VAL ? true : false;
                }

                // Show command window
                if (line.StartsWith(SHOW_COMMAND_MARK))
                {
                    string val = this.GetLineVal(line, SHOW_COMMAND_MARK).ToLower();
                    config.ShowCommandWindow = val == ON_VAL ? true : false;
                }

                // MSpec location
                if (line.StartsWith(MPSPEC_LOCATION_MARK))
                {
                    string val = this.GetLineVal(line, MPSPEC_LOCATION_MARK);
                    config.MSpecLocation = val;
                }

                // Assembly
                if (line.StartsWith(ASSEMBLY_MARK))
                {
                    string val = this.GetLineVal(line, ASSEMBLY_MARK);
                    config.Assemblies.Add(val);
                }

                // Output folder
                if (line.StartsWith(OUTPUT_FOLDER_MARK))
                {
                    string val = this.GetLineVal(line, OUTPUT_FOLDER_MARK);
                    config.OutputFolder = val;
                }
            }

            // If config is not complete, return null
            if (!config.IsComplete()) config = null;

            return config;
        }

        private string GetLineVal(string line, string mark)
        {
            return line.Substring(mark.Length).Trim();
        }

    }
}
